<?php

namespace app\models;

use Yii;
use Overtrue\Wechat\QRCode;
use app\common\utils\HttpClient;
use yii\web\UploadedFile;

/**
 * This is the model class for table "gky_qyh".
 *
 * @property integer $id
 * @property string $qyhname
 * @property string $corpid
 * @property string $qrcode
 * @property string $logo
 * @property string $addtime
 * @property string $accesstoken
 * @property string $expiretime
 * @property string $secret
 * @property string $aeskey
 */
class GkyQyh extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gky_qyh';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['addtime', 'expiretime'], 'integer'],
            [['qyhname', 'corpid'], 'string', 'max' => 128],
            [['qrcode', 'logo', 'accesstoken', 'secret'], 'string', 'max' => 256],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'qyhname' => '企业号',
            'corpid' => 'Corpid',
            'qrcode' => 'Qrcode',
            'logo' => '图标',
            'addtime' => 'Addtime',
            'accesstoken' => 'Accesstoken',
            'expiretime' => 'Expiretime',
            'secret' => 'Secret',
        ];
    }

    public static function findQrcodeById($id){

        $weaccount = GkyWeAccount::find()->where(['id'=>$id])->one();
        if($weaccount->qrcode == null){
            $qrcode = new QRCode($weaccount->weappid, $weaccount->wesecret);
            $result = $qrcode->forever(56);// 或者 $qrcode->forever("foo");
            $ticket = $result->ticket;
            $weaccount->qrcode = $qrcode->show($ticket);
            $weaccount->save();
        }

        return $weaccount->qrcode;
    }

    public function getToken(){

        if($this->expiretime == null || $this->expiretime < time()){
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='
                .$this->corpid.'&corpsecret='.$this->secret;
            $result = HttpClient::get($url);
            $this -> accesstoken = $result -> access_token;
            $this -> expiretime = $result -> expires_in + time();
            $this->save();
            return $result -> access_token;
        }else{
            return $this->accesstoken;
        }
    }
    
    public function beforeSave($insert){
        if (parent::beforeSave($insert)) {
            $path=  \Yii::$app->request->post("files");
            $this->qrcode=$path[0];
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据corpid查询企业号
     *
     * @param $corpid
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function findByCorpid($corpid){

        return GkyQyh::find()->where(['corpid'=>$corpid])->one();
    }
}
